import OpenAI from 'openai'
import { BaseProvider } from './base-provider'
import { ConverContentProps, MessageContent, UniversalProps } from '../type'
import { coverContent } from '../helper'
export class DeepSeakProvider extends BaseProvider {
  private client: OpenAI
  constructor(apiKey: string, baseURL: string) {
    super()
    this.client = new OpenAI({
      apiKey,
      baseURL
    })
  }
  async chat(message: ConverContentProps, model: string): Promise<any> {
    const coverMessage = await coverContent(message)
    const stream = await this.client.chat.completions.create({
      model,
      messages: coverMessage,
      stream: true
    })
    const self = this
    return {
      async *[Symbol.asyncIterator]() {
        for await (const part of stream) {
          yield self.transformResponse(part)
        }
      }
    }
  }
  protected transformResponse(chunk: OpenAI.Chat.Completions.ChatCompletionChunk): UniversalProps {
    const choices = chunk.choices[0]
    return {
      is_end: choices.finish_reason ? true : false,
      result: choices.delta.content || ''
    }
  }
}
